import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { createToggleHeaderAction } from '@/redux/actions/headerVisible'
import { NavBar, Icon } from 'antd-mobile'
import MenuBar from '@/components/MenuBar'
import LoadMore from '@/components/LoadMore'
import Cover from '@/components/Cover'
import config from '@/router/config'
import { rankApi } from '@/api'
import css from './index.module.scss'
class Rank extends PureComponent {
    constructor(props) {
        super(props)
        this.state = this.initState()
    }
    listRef = React.createRef()
    
    initState = () => {        
        const tabs = []
        let currentTab = 0
        const id = this.getId()       
        for (const [index, c] of Object.entries(config)) {
            const { name, tid, route, hide } = c
            if (hide) {
                continue
            }
            if (tid === (id - 0)) {
                currentTab = index - 0
            }
            tabs.push({
                tid,
                name: name === '首页' ? '全站' : name,
                path: route === '/' ? '/rank' : `/rank/${tid}`,
                currentPage: 1,
                totalPage: 0,
                pageSize: 20,
                list: []
            })
        }
        return {
            currentTab,
            tabs
        }
    }

    getCurrent = () => {
        const { currentTab, tabs } = this.state
        return tabs[currentTab]
    }

    getId = () => {
        let realId = 0
        const { match: { params: { id } } } = this.props  
        if (id) {
            realId = id - 0
        } 
        return realId
    }

    getRid = () => {
        let rid = 0
        const id = this.getId()
        rid = id === 167 ? 168 : id
        return rid
    }

    getData = async () => {
        try {
            this.startLoading()
            const { data } = await rankApi.getRank({
                rid: this.getRid()
            })
            const { list } = data
            if (!Array.isArray(list)) {
                return
            }
            if (list.length === 0) {
                this.complete()
            } else {
                const current = this.getCurrent()
                current.totalPage = Math.ceil(list.length / current.pageSize)
                current.list = list
                this.setState({
                    tabs: [...this.state.tabs]
                })
            }            
        } catch (error) {
            
        } finally {
            this.stopRefresh()
            this.stopLoading()
        }
    }

    handleTab = tab => {
        this.props.history.push(tab.path)
    }

    handleBack = () => {
        this.props.history.go(-1)
    }

    startLoading = () => {
        this.listRef?.current?.startLoading()
    }
    stopLoading = () => {
        this.listRef?.current?.stopLoading()
    }
    stopRefresh = () => {
        this.listRef?.current?.stopRefresh()
    }
    complete = () => {
        this.listRef?.current?.complete()
    }

    onReachEnd = () => {
        const current = this.getCurrent()
        const { totalPage, currentPage } = current
        if (currentPage < totalPage) {
            current.currentPage = currentPage + 1
            this.setState({
                tabs: [...this.state.tabs]
            })
        } else {
            this.complete()
        }
    }

    onRender = (rowData, sectionId, rowId) => {
        return (
            <div className={css["row"]}>
                <div className={css["order"]}>{rowId - 0 + 1}</div>
                <Cover 
                    className={css["content"]}
                    key={rowData.bvid} 
                    direction="horizontal"
                    danmaku={rowData.video_review}                
                    {...rowData} 
                />
            </div>
        )
    }

    onRefresh = () => {
        const current = this.getCurrent()
        current.currentPage = 1        
        this.setState({
            tabs: [...this.state.tabs]
        }, () => {
            this.getData()
        })
    }

    componentDidMount() {
        this.props.toggleHeader(false)
        this.getData()
    }

    componentDidUpdate(prevProps) {                
        const id = this.getId()    
        let prevId = prevProps.match.params.id    
        prevId = prevId ? (prevId - 0) : 0
        if (id !== prevId) {
            let currentTab = 0
            if (id) {
                currentTab = this.state.tabs.findIndex(item => item.tid === (id - 0))
                currentTab = currentTab < 0 ? 0 : currentTab
            }
            this.setState({
                currentTab
            }, () => {
                const { list } = this.getCurrent()
                if (!list.length) {
                    this.getData()
                }                
            })
        } 
        
    }

    componentWillUnmount() {
        this.props.toggleHeader(true)
    }

    render() {
        const { tabs, currentTab } = this.state
        const { currentPage, pageSize, list } = this.getCurrent()
        const pageList = list.slice(0, currentPage * pageSize)
        return (
            <>
                <div className={css["sticky"]}>
                    <NavBar 
                        mode="light"
                        icon={<Icon type="left" />}
                        onLeftClick={this.handleBack}
                    >排行榜</NavBar>
                    <MenuBar 
                        tabs={tabs} 
                        currentTab={currentTab} 
                        onTabClick={this.handleTab} 
                    />
                </div>
                <LoadMore                    
                    ref={this.listRef}
                    data={pageList}  
                    onRefresh={this.onRefresh}                
                    onReachEnd={this.onReachEnd}
                    renderRow={this.onRender}
                />
            </>
        )
    }
}

export default connect(
    null,
    {
        toggleHeader: createToggleHeaderAction
    }
)(Rank)
